//
//  WechatCodeViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/12/16.
//

#import "WechatCodeViewController.h"

@interface WechatCodeViewController ()
@property(nonatomic,strong)UIImageView *codeImageView;
@property(nonatomic,strong)UIButton *saveBtn;
@end

@implementation WechatCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}

-(void)createUI{
    
    [self.customNavigationBar setTitle:@"微信二维码"];
    
    CGFloat w254 = [DeviceUtils getAdaptedWidthForDesignWidth:254 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(w254 > 400){
        w254 = 400;
    }
    CGFloat h120 = [DeviceUtils getAdaptedHeightForDesignHeight:120 andCurrentAvailableHeight:self.currentAvailableHeight];
    CGFloat h65 = [DeviceUtils getAdaptedHeightForDesignHeight:65 andCurrentAvailableHeight:self.currentAvailableHeight];
    
    UIImageView *codeImageView = [[UIImageView alloc]init];
    codeImageView.layer.cornerRadius = 12;
    codeImageView.layer.masksToBounds = YES;
    codeImageView.image = [UIImage imageNamed:@"wechatcode"];
    [self.view addSubview: codeImageView];
    __weak typeof(self)self_weak_  = self;
    [codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(w254);
        make.centerX.mas_equalTo(self_weak_.view);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+h120);
    }];
    self.codeImageView = codeImageView;
    
    CGFloat w122 = [DeviceUtils getAdaptedWidthForDesignWidth:122 andCurrentAvailableWidth:self.currentAvailableWidth];
    UIButton *saveBtn = [[UIButton alloc]init];
    saveBtn.backgroundColor = KThemeColor;
    [saveBtn setTitle:@"保存二维码" forState:UIControlStateNormal];
    saveBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 18;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(w122);
        make.height.mas_equalTo(@36);
        make.top.mas_equalTo(codeImageView.mas_bottom).offset(h65);
        make.centerX.mas_equalTo(self_weak_.view);
    }];
    self.saveBtn = saveBtn;
    
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat w254 = [DeviceUtils getAdaptedWidthForDesignWidth:254 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(w254 > 400){
                w254 = 400;
            }
            CGFloat h120 = [DeviceUtils getAdaptedHeightForDesignHeight:120 andCurrentAvailableHeight:self.currentAvailableHeight];
            CGFloat h65 = [DeviceUtils getAdaptedHeightForDesignHeight:65 andCurrentAvailableHeight:self.currentAvailableHeight];
            CGFloat w122 = [DeviceUtils getAdaptedWidthForDesignWidth:122 andCurrentAvailableWidth:self.currentAvailableWidth];
            [self.codeImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(w254);
            }];
            __weak typeof(self)self_weak_  = self;
            [self.saveBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(w122);
                make.top.mas_equalTo(self_weak_.codeImageView.mas_bottom).offset(h65);
            }];
           
        });
    }
}

-(void)saveBtnClick{
    __weak typeof(self)self_weak_ = self;
    [self isCanVisitPhotoLibrary:^(BOOL iscan) {
        if (iscan == YES) {
            [self_weak_ saveConfig];
        }else{
            [JPProgressHUD showMsg:@"未开启相册权限，请到设置中开启"];
        }
    }];
    
    
}

#pragma mark - 相册权限检测
-(void)isCanVisitPhotoLibrary:(void(^)(BOOL))result{
   PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
   if (status == PHAuthorizationStatusAuthorized) {
       result(YES);
       return;
   }
   if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
       result(NO);
       return ;
   }
   
   if (status == PHAuthorizationStatusNotDetermined) {
       
       [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
           // 回调是在子线程的
//           NSLog(@"%@",[NSThread currentThread]);
           dispatch_async(dispatch_get_main_queue(), ^{
               if (status != PHAuthorizationStatusAuthorized) {
//                     NSLog(@"未开启相册权限,请到设置中开启");
                     result(NO);
                     return ;
                 }
                 result(YES);
           });
 
       }];
   }
   
}

#pragma mark - 保存截图
-(void)saveConfig{
    UIImage *lastImage = [UIImage imageNamed:@"wechatcode"];
    if(lastImage){
        UIImageWriteToSavedPhotosAlbum(lastImage,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);
    }
}

#pragma mark - 图片保存状态
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        [JPProgressHUD showMsg:@"保存成功"];
    }else{
        [JPProgressHUD showMsg:@"保存失败"];
    }
}


@end
